package grpc_module

import (
	"context"
	"gitee.com/kmyss/gf-ex/ysgrpc"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/gf-ex/ysutils"
	"gitee.com/kmyss/ys-cli/internal/model"
	"gitee.com/kmyss/ys-cli/internal/service"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gproc"
	"github.com/gogf/gf/v2/util/gutil"
	"os"
	"sync"
)

func init() {
	service.RegisterGrpcModule(&sGrpcModule{})
}

type iModule interface {
	ysgrpc.IMQModule
	setParam(*gmap.StrAnyMap)
}

type sGrpcModule struct {
	l *glog.Logger // 日志
}

func (s *sGrpcModule) log() *glog.Logger {
	if s.l == nil {
		s.l = yslog.Log("logic.grpc-module")
	}
	return s.l
}

func (s *sGrpcModule) Run(ctx context.Context, config *model.GrpcModuleCfgInput) error {

	wg := &sync.WaitGroup{}
	ysutils.ProcInstanceListen()

	// 文件管理
	if config.RunFile.Has {
		wg.Add(1)
		go func() {
			s.runModel(ctx, config.RunFile.Param, newFileModule())
			wg.Done()
		}()
	}

	if config.RunWatch.Has {
		wg.Add(1)
		go func() {
			s.runModel(ctx, config.RunWatch.Param, newWatchModule())
			wg.Done()
		}()
	}

	wg.Wait()

	s.log().Info(ctx, "停止运行")

	return nil
}

func (s *sGrpcModule) runModel(ctx context.Context, param *gmap.StrAnyMap, module iModule) {
	s.log().Infof(ctx, "启动 %s 模块", module.Cfg().Name)
	s.log().Debug(ctx, "输入参数:")
	if s.log().GetLevel()&glog.LEVEL_DEBU > 0 {
		g.DumpTo(s.log(), param, gutil.DumpOption{})
	}

	gproc.AddSigHandlerShutdown(func(sig os.Signal) {
		module.Stop()
	})

	module.setParam(param)
	module.Init(ctx)
	module.Run()
}
